using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.HostedServices
{
    /// <summary>
    /// 延迟附加重量级日志 sink 的后台服务（示例占位）。
    /// Phase-1 目标：把潜在的慢初始化工作放到后台执行，缩短主机启动关键路径。
    /// 后续可在这里：
    /// 1. 分离 core logger 与 heavy logger（DB、Elastic、Seq 等）。
    /// 2. 预热数据库/缓存/编译表达式树。
    /// </summary>
    public class LoggingSinkAttachHostedService : IHostedService
    {
        private readonly ILogger<LoggingSinkAttachHostedService> _logger;
        private readonly IConfiguration _configuration;
        private readonly IServiceProvider _serviceProvider;

        public LoggingSinkAttachHostedService(
            ILogger<LoggingSinkAttachHostedService> logger,
            IConfiguration configuration,
            IServiceProvider serviceProvider)
        {
            _logger = logger;
            _configuration = configuration;
            _serviceProvider = serviceProvider;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var enabled = _configuration.GetValue("Logging:Deferred:Enable", true);
            if (!enabled)
            {
                _logger.LogInformation("[DeferredLogging] 已禁用跳过附加重量级 sink。");
                return;
            }

            var delaySeconds = _configuration.GetValue("Logging:Deferred:DelaySeconds", 2);
            if (delaySeconds > 0)
            {
                try
                {
                    await Task.Delay(TimeSpan.FromSeconds(delaySeconds), cancellationToken);
                }
                catch (TaskCanceledException) { }
            }

            var start = DateTime.UtcNow;
            try
            {
                Log.Information("[DeferredLogging] 开始附加重量级日志组件…");
                // 附加重型 sinks
                EnhancedSerilogConfigurator.AttachHeavySinks();
                Log.Information("[DeferredLogging] 重量级日志组件附加完成。耗时 {Elapsed}ms", (DateTime.UtcNow - start).TotalMilliseconds);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "[DeferredLogging] 附加重量级日志组件失败。");
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            // 无需清理；如果未来添加外部资源，可在此处释放。
            return Task.CompletedTask;
        }
    }
}
